<template>
  <div id="userLoginView">
    <h2 style="margin-bottom: 16px">用户登录</h2>
    <a-form
        style="max-width: 480px; margin: 0 auto"
        label-align="left"
        auto-label-width
        @submit="userLogin"
    >
      <a-form-item field="userAccount" label="账号">
        <a-input placeholder="请输入账号" v-model="userLoginRequest.userAccount"/>
      </a-form-item>
      <a-form-item field="userPassword" tooltip="密码不少于 8 位" label="密码">
        <a-input-password
            placeholder="请输入密码"
            v-model="userLoginRequest.userPassword"
        />
      </a-form-item>
      <a-form-item icon-align-center>
        <a-button html-type="submit" type="primary" style="width: 100%">
          登录
        </a-button>
      </a-form-item>
      <a-form-item icon-align-center>
        <a-button type="primary" style="width: 100%" @click="toRegister">
          注册
        </a-button>
      </a-form-item>
    </a-form>
  </div>
</template>

<script setup>
import {reactive} from "vue";
import {userLoginUsingPost} from "@/api/UserRequest";
import message from "@arco-design/web-vue/es/message";
import {useRouter} from "vue-router";
import {useLoginUserStore} from "@/store/userStore";

const userLoginRequest = reactive({
  userAccount: "",
  userPassword: "",
});

const router = useRouter();
const loginUserStore = useLoginUserStore();

async function userLogin() {
  const result = await userLoginUsingPost(userLoginRequest);
  if (result.data.code === 0) {
    // TODO 定义用于存储用户登录信息的对象
    await loginUserStore.fetchLoginUser();
    message.success("登录成功");
    if(result.data.data.userRole === 'admin'){
      router.push({
        path: "/admin/home",
        replace: true,
      });
    }else {
      router.push({
        path: "/home",
        replace: true,
      });
    }

  } else {
    message.error("登录失败，" + result.data.message);
  }
}

function toRegister(){
  router.push("/user/register");
}
</script>